package com.big.sms.advice;

import com.big.common.exception.BaseException;
import com.big.common.exception.SmsException;
import com.big.common.result.SmsResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.file.AccessDeniedException;
import java.sql.SQLException;

/**
 * 异常处理
 */
@ResponseBody
@Slf4j
@ControllerAdvice
public class DefaultExceptionAdvice {
    /**
     * IllegalArgumentException异常处理返回json
     */
    @ExceptionHandler({IllegalArgumentException.class})
    public SmsResult badRequestException(IllegalArgumentException e) {
        return defHandler("参数解析失败", e);
    }

    /**
     * AccessDeniedException异常处理返回json
     */
    @ExceptionHandler({AccessDeniedException.class})
    public SmsResult badMethodExpressException(AccessDeniedException e) {
        return defHandler("没有权限请求当前方法", e);
    }

    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public SmsResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return defHandler("不支持当前请求方法", e);
    }

    /**
     * SQLException sql异常处理
     */
    @ExceptionHandler({SQLException.class})
    public SmsResult handleSQLException(SQLException e) {
        return defHandler("服务运行异常", e);
    }

    /**
     * 所有异常统一处理
     */
    @ExceptionHandler(Exception.class)
    public SmsResult handleException(Exception e) {
        return defHandler("未知异常", e);
    }

    private SmsResult defHandler(String msg, Exception e) {
        return SmsResult.fail(msg);
    }

    @ExceptionHandler(SmsException.class)
    public SmsResult smsException(SmsException e) {
        return new SmsResult(String.valueOf(e.getCodeAndMessage()), e.getData());
    }

    @ExceptionHandler(BaseException.class)
    public SmsResult baseException(BaseException e) {
        return new SmsResult(String.valueOf(e.getCodeAndMessage()), e.getData());
    }
}
